#encoding:utf8 

import sublime, sublime_plugin
import string
import os
import json
import re
from .newfile.constant import TEMPLATE_MAP


class IronInsertCommand(sublime_plugin.TextCommand):
	def run(self, edit, cont=""): 
		self.view.insert(edit, 0, cont)



# create file by template 
class IronNewCommand(sublime_plugin.WindowCommand):

	def run(self, **kwads):

		self._lan = ""
		self._templates = {}
		lan_types = list(TEMPLATE_MAP.keys())

		def on_sel_ltype(selval):

			if selval < 0:
				return 
			lan = lan_types[selval]
			templates = list(TEMPLATE_MAP[lan].keys())
			self._lan = lan
			self.window.show_quick_panel(templates, self.__sel_template)

		# sel template type
		self.window.show_quick_panel(lan_types, on_sel_ltype)


	def __sel_template(self, selval):
		if selval < 0:
			return 
		tempname = list(TEMPLATE_MAP[self._lan].keys())[selval]
		temp_file = TEMPLATE_MAP[self._lan][tempname]
		print("create file by template ->%s.."%temp_file)
		path_temp_file = os.path.join(sublime.packages_path(), "User", "newfile", self._lan, temp_file) 
		if not os.path.isfile(path_temp_file):
			sublime.error_message("not find template-file<%s> in path "%path_temp_file)
			return 

		BASE_PARAMS = '''{"clsname":"xx"}'''

		def on_input_done(txtval):
			try:
				ret = json.loads(txtval) 
			except Exception as e:
				sublime.error_message(str(e))
				raise e
			# clslit 
			if "clsname" in ret: 
				par = re.compile("[A-Z]+")
				ret["clslit"] = "".join(par.findall(ret["clsname"])).lower()
			if (isinstance(ret, dict)):
				self.__handle_template(path_temp_file, ret)

		self.window.show_input_panel("Template ValueMap", BASE_PARAMS, on_input_done, None, None)
		

		 
	def __handle_template(self, pfile, valmap={}):
		# chk require 
		if "clsname" not in valmap:
			sublime.error_message("clsname is required to create tempalte.\n Failed!")
			return 

		cont = ""
		with open(pfile, "r+", encoding='utf-8')  as fp:
			cont = fp.read()
			cont = self.__rep_val(cont, valmap)

		nf = self.window.new_file()
		nf.set_name(valmap.get("clsname").lower() + ".lua")
		self.window.run_command("iron_insert", {"cont":cont})

	def __rep_val(self, cont, valmap):
			varfmt = "$%s"

			for k in valmap.keys():
				print("replace valu from=%s, to=%s"%(k, valmap[k]))
				cont = cont.replace(varfmt%k, valmap[k])
			return cont